package com.shigen.demo.algorithm;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.Currency;
import java.util.Locale;

/**
 * @author shigenfu
 * @date 2023/9/26 2:23 下午
 */
public class BigDecimalUtil {

    // 创建适合当前区域设置的货币格式化实例
    public static final NumberFormat CURRENCY_INSTANCE = NumberFormat.getCurrencyInstance(Locale.CHINA);

    public static final NumberFormat NUMBER_INSTANCE = NumberFormat.getNumberInstance();

    public static final NumberFormat PERCENT_INSTANCE = NumberFormat.getPercentInstance();

    /**
     * 将货币格式化实例设置为人民币
     */
    public static String formatToYmb(BigDecimal number) {
        Currency cnyCurrency = Currency.getInstance("CNY");
        CURRENCY_INSTANCE.setCurrency(cnyCurrency);
        return CURRENCY_INSTANCE.format(number);
    }

    /**
     * 获取适合当前区域设置的数字格式化实例，带千位分隔符
     *
     * @param number 数字
     * @return 带千位符的字符串
     */
    public static String formattedWithGrouping(BigDecimal number) {
        return NUMBER_INSTANCE.format(number);
    }

    /**
     * 百分比格式化
     *
     * @param number 数字
     * @return 百分比格式化之后的数字
     */
    public static String formattedPercent(BigDecimal number) {
        return PERCENT_INSTANCE.format(number);
    }

    /**
     * 设置小数位数，四舍五入
     *
     * @param number 数字
     * @param scale  位数
     * @return 四舍五入之后的位数
     */
    public static BigDecimal setScale(BigDecimal number, int scale) {
        return number.setScale(scale, RoundingMode.HALF_UP);
    }

    public static void main(String[] args) {
        BigDecimal number = new BigDecimal("14354.333490009");
        System.out.println(number);
        System.out.println(formatToYmb(number));
        System.out.println(formattedWithGrouping(number));
        System.out.println(formattedPercent(number));
        System.out.println(setScale(number, 4));
    }
}
